<!--
  企业招聘管理-职位下，所有投递简历列表
 -->
<template>
  <div class="app-container">
    <el-form
      ref="queryForm"
      :model="queryForm"
      size="small"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="投递时期" prop="date">
        <el-date-picker
          v-model="queryForm.date"
          type="daterange"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd hh:mm:ss"
          :picker-options="pickerOptions"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryForm.status" clearable>
          <el-option
            v-for="item in resumeStatus"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="来源" prop="source">
        <el-select v-model="queryForm.source" clearable>
          <el-option
            v-for="item in resumeSource"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="handleQuery"
        >搜索</el-button>
      </el-form-item>
    </el-form>
    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="multipleSelection.length"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleInvite(null)"
        >批量发送面试邀约</el-button>
      </el-col>
    </el-row>
    <!-- 列表 -->
    <el-table
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" type="index" />
      <el-table-column label="姓名" align="center" prop="studentName" />
      <el-table-column label="年龄" align="center" prop="birthday" />
      <el-table-column label="学历" align="center" prop="education" />
      <el-table-column label="所学专业" align="center" prop="major" />
      <el-table-column label="性别" align="center" prop="sex" />
      <el-table-column label="居住地" align="center" prop="liveCity" />
      <el-table-column label="来源" align="center" prop="source">
        <template slot-scope="scope">
          {{ getResumeSource(scope.row.source) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          {{ getResumeStatus(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column
        label="投递日期"
        align="center"
        prop="postDate"
        width="180"
        sortable
      >
        <template slot-scope="scope">
          <span>{{ moment(scope.row.postDate).format('yyyy-MM-DD') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- 简历状态，resumeStatus（投递过程的工单状态）0 未查看简历、1 已查看简历、2 已发送面试邀约、3 已确认面试邀约、4 已拒绝面试邀约、5 已面试反馈（企业）、6 已评价（学生） -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleCheck(scope.row)"
          >查看</el-button>
          <el-button
            v-if="Number(scope.row.status) < 2"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleInvite(scope.row)"
          >面试邀约</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryForm.pageNo"
      :limit.sync="queryForm.pageSize"
      :page-sizes="[10]"
      @pagination="getList"
    />
    <InviteDialog
      ref="InviteDialog"
      @close="getList"
      @submit="createInterview"
    />
  </div>
</template>

<script>
import {
  getpageByJob,
  createInvite
} from '@/api/company-admin-api/hireManage/index.js'
import { resumeSource, resumeStatus } from '@/utils/frontDataDict.js'
import moment from 'moment'
import { deepClone } from '../../../../utils'
import InviteDialog from './inviteDialog.vue'
export default {
  name: 'ResumeListDialog',
  components: {
    InviteDialog
  },
  props: {
    job: {
      type: [Object]
    }
  },
  data() {
    return {
      moment: moment,
      resumeSource: resumeSource,
      resumeStatus: resumeStatus,
      // 遮罩层
      loading: true,
      list: [],
      // 总条数
      total: 0,
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const start = moment()
                .startOf('day')
                .subtract(6, 'days')
                .format('yyyy-MM-DD HH:mm:ss')
              const end = moment().endOf('day').format('yyyy-MM-DD HH:mm:ss')
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const start = moment()
                .startOf('day')
                .subtract(1, 'months')
                .format('yyyy-MM-DD HH:mm:ss')
              const end = moment().endOf('day').format('yyyy-MM-DD HH:mm:ss')
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近半年',
            onClick(picker) {
              const start = moment()
                .startOf('day')
                .subtract(6, 'months')
                .format('yyyy-MM-DD HH:mm:ss')
              const end = moment().endOf('day').format('yyyy-MM-DD HH:mm:ss')
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      // 查询参数
      queryForm: {
        pageNo: 1,
        pageSize: 10,
        source: null, // 来源
        status: null, // 简历状态
        date: [] // 投递日期
      },
      beginPostDate: '', // 投递开始时间
      endPostDate: '', // 投递结束时间
      currentResumeRow: null,
      multipleSelection: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleSelectionChange(val) {
      this.multipleSelection = []
      val.map((item) => {
        if (Number(item.status) < 2) {
          this.multipleSelection.push(item)
        }
      })
    },
    filterEmptyParam(obj) {
      const newObj = {}
      for (const key in obj) {
        if (obj[key] !== null && obj[key] !== '') {
          newObj[key] = obj[key]
        }
      }
      return newObj
    },
    /**
     * @desc 批量创建面试邀约
     * @param {Object} data 统一的面试邀约条件，后续组装到所有的批量数据里
     */
    createInterview(data) {
      let multipleSelection
      if (this.currentResumeRow === null) {
        // 多个邀约
        multipleSelection = deepClone(this.multipleSelection)
      } else {
        // 单个邀约
        multipleSelection = [this.currentResumeRow]
      }
      multipleSelection = multipleSelection.map((item) => {
        const interviewItem = {
          companyId: '', // 企业id
          companyName: '', // 企业名称
          deptId: '', // 部门id,
          email: '', // 邮箱
          evaluation: '', // 面试评价
          feedback: '', // 学生评价/原因,
          inviteAddress: '', // 面试地址
          inviteContent: '', // 面试描述内容,
          inviteDate: '', // 面试邀约日期
          inviteResult: '', // 原因
          inviteWay: '', // 邀约方式
          jobId: '', // 职位id
          jobName: '', // 职位名称
          noticeItem: '', // 注意事项
          phoneNumber: '', // 手机号
          publisherId: '', // 发布人id
          publisherName: '', // 发布人姓名
          sendRecordId: '', // 发送记录id
          status: '', // 状态
          studentId: '', // 学生id
          studentName: '', // 学生姓名
          userId: '', // 用户id
          resumeId: '', // 简历id
          isSendMsg: false // 是否发送短信提示
        }
        Object.assign(item, data)
        for (const key in interviewItem) {
          if (Object.hasOwnProperty.call(item, key)) {
            interviewItem[key] = item[key]
          }
        }
        interviewItem.sendRecordId = item.id
        interviewItem.isSendMsg = interviewItem.isSendMsg ? '1' : '0'
        return interviewItem
      })
      createInvite(multipleSelection).then((res) => {
        if (res.code === 0 && res.data) {
          this.$refs.InviteDialog.close()
        }
      })
    },
    /** 打开应聘详情 */
    handleCheck(row) {
      this.$emit('checkDetail', row)
    },
    // 打开面试邀约弹窗
    handleInvite(row = null) {
      if (row !== null) {
        // 单个
        this.currentResumeRow = deepClone(row)
      } else {
        // 批量
        this.currentResumeRow = null
      }
      this.$refs.InviteDialog.open()
    },
    // 返回简历状态
    getResumeStatus(status) {
      const result = this.resumeStatus.find(
        (item) => Number(item.value) === Number(status)
      )
      return (result && result.label) || '--'
    },
    // 返回简历来源展示文本
    getResumeSource(status) {
      const result = this.resumeSource.find(
        (item) => Number(item.value) === Number(status)
      )
      return (result && result.label) || '--'
    },
    // 返回年龄
    getAge(birthday) {
      // 出生时间 毫秒
      var birthDayTime = new Date(birthday).getTime()
      // 当前时间 毫秒
      var nowTime = new Date().getTime()
      // 一年毫秒数(365 * 86400000 = 31536000000)
      return Math.floor((nowTime - birthDayTime) / 31536000000)
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      // 处理查询参数
      let params = deepClone(this.queryForm)
      delete params.date
      params.jobId = this.job.id
      if (this.queryForm.date.length === 2) {
        params.beginPostDate = this.queryForm.date[0]
        params.endPostDate = this.queryForm.date[1]
      }
      params = this.filterEmptyParam(params)
      // 执行查询
      getpageByJob(params).then((res) => {
        const list = deepClone(res.data.list).map((item) => {
          item.birthday = this.getAge(item.birthday)
          // try {
          //   item.educationalExperience = JSON.parse(item.educationalExperience)
          // } catch (error) {
          //   console.error(new Error('教育经历不存在'))
          // }
          if (
            Array.isArray(item.educationalExperience) &&
            item.educationalExperience.length
          ) {
            const educate = ['大专', '本科', '硕士', '博士']
            educate.map((iten) => {
              const matchEducate = item.educationalExperience.find(
                (single) => single.educationalBackground.indexOf(iten) > -1
              )
              if (matchEducate) {
                item.schoolName = matchEducate.schoolName // 学校名称
                item.major = matchEducate.major // 专业
                item.education = iten // 学历
              }
            })
          } else {
            item.schoolName = '--' // 学校名称
            item.major = '--' // 专业
            item.education = '--' // 学历
          }
          return item
        })
        this.list = list
        this.total = res.data.total
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryForm.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    }
  }
}
</script>
